package io.renren.modules.common;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.renren.common.pojo.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public abstract class BaseCrudServiceImpl<D extends BaseDao<E>,E extends BaseEntity>
        extends BaseService implements BaseCrudService<E>{

    @Autowired
    protected D dao;

    @Override
    public List<E> queryList(Query query) {
        return dao.selectAll();
    }

    @Override
    public PageInfo<E> queryPage(Query query) {
        String orderBy = query.getOrderBy();
        return PageHelper.startPage(query.getPage(),query.getLimit())
                .setOrderBy(orderBy)
                .doSelectPageInfo(() -> dao.selectAll());
    }

    @Override
    public long queryTotal() {
        return PageHelper.count(() -> dao.selectAll());
    }

    @Override
    public E queryById(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public E save(E entity) {
        boolean isSuccess;
        if(entity.getId() == null){
            isSuccess = dao.insertUseGeneratedKeys(entity) > 0;
        }
        else {
            isSuccess = dao.updateByPrimaryKeySelective(entity) > 0;
        }

        return isSuccess ? queryById(entity.getId()) : null;
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        return dao.deleteByPrimaryKey(id) > 0;
    }

    @Override
    @Transactional
    public boolean deleteBatch(Integer[] ids) {
        int deleteNumber = 0;
        for(Integer id : ids){
            if(dao.deleteByPrimaryKey(id) > 0){
                deleteNumber ++;
            }
        }
        return deleteNumber == ids.length;
    }
}
